package com.stupidzhe.jdklearning.generic;

/**
 * Created by Mr.W on 2017/11/3.
 * 创建一个链式堆栈
 */
public class LinkedStack<T> {

    private Node<T> node;

    private class Node<T> {
        private T element;
        private Node<T> next;
        Node() {
            element = null;
            next = null;
        }

        Node(T element, Node<T> next) {
            this.element = element;
            this.next = next;
        }
    }

    public LinkedStack() {
        node = new Node<>();
    }

    public T push(T element) {
        this.node = new Node<>(element, this.node);
        return element;
    }

    public T poll() {
        if (this.node == null || this.node.element == null) {
            return null;
        }
        T tmpElement = this.node.element;
        this.node = this.node.next;
        return tmpElement;
    }

    public T peek() {
        if (this.node == null || this.node.element == null) {
            return null;
        }
        return this.node.element;
    }

    public static void main(String[] args) {
        LinkedStack<String> stack = new LinkedStack<>();
        stack.push("1");
        stack.push("2");
        stack.push("3");
        System.out.println(stack.peek());
        System.out.println(stack.poll());
        System.out.println(stack.poll());
        System.out.println(stack.poll());
        System.out.println(stack.poll());
    }

}
